$(function() {
  var app = {
    openId: GetRequest().openId,
    hostSever: getServerHost(),
    myScratchCardPrize: '/api/longtaitou/myScratchCardPrize',
    scratchCard: '/api/longtaitou/scratchCard',
    scratchCardPrize: '/api/longtaitou/scratchCardPrize',
    prizeImg: ['./images/ticket-no.png', './images/ticket-yes.png'],
    ticketBg: '',
    sendInfo: '',
    init: function() {
      app.initCard();
      app.clickGroup();
    },
    clickGroup:function(){
      $('.reback').click(function(){
        location.href='./index.html?openId='+app.openId;
      })
    },
    initCard: function() {
      // 获取打卡信息
      $.get(app.hostSever + app.myScratchCardPrize, {
        openId: app.openId
      }).done(function(rp) {
        $('.loading').hide();
        console.log(Boolean(rp['res']));
        if (!Boolean(rp['res'])) {
          //没有参加过游戏
          $('#startGameBtn').on('click', app.getPrizeRecord);
        } else {
          if (0 == rp.res.status) {
            $('#myc').empty().css({
              'backgroundImage': "url('" + app.prizeImg[0] + "')"
            });
            autoshowBar('.noGoods');
            closeBar('#noPrize', '.noGoods');
            $('#myc').off('click').on('click', function() {
              autoshowBar('.noGoods');
            })
          } else {
            $('#myc').empty().css({
              'backgroundImage': "url('" + app.prizeImg[1] + "')"
            });
            if (!Boolean(rp.res.mobile)) {
              autoshowBar('.writePhone');
              $('#writePhone').off('click');
              $('#writePhone').on('click', app.sendPhone);
            } else {
              $('#pPhone').text(rp.res.mobile);
              autoshowBar('.haveprize');
              closeBar('#closePrize', '.haveprize');
              $('#myc').off('click').on('click', function() {
                autoshowBar('.haveprize');
              })
            }
          }
        }
      }).fail(function(rp) {})
    },

    getPrizeRecord: function() {
      $('.loading').show();
      $.ajax({
        type: 'get',
        data: {
          openId: app.openId
        },
        url: app.hostSever + app.scratchCard,
        beforesend: function() {
        },
        complete: function() {
          $('.loading').hide();
        },
        success: function(rp) {
          if (200 == rp.res.code) {
            app.ticketBg = app.prizeImg[1];
            $('#myCanvas').attr('key', 1);
            app.initCanvas();
          } else if (206 == rp.res.code) {
            app.ticketBg = app.prizeImg[0];
            $('#myCanvas').attr('key', 0);
            app.initCanvas();
          } else if (999 == rp.code) {
            alert(rp.msg);
          }

        },
        error: function(rp) {}
      })
    },
    sendPhone: function() {
        $('.loading').show();
      if (!checkMobile($('#mPhone').val())) {
        alert('请输入11位手机号');
        return;
      }
      $.ajax({
        type: 'get',
        url: app.hostSever + app.scratchCardPrize,
        data: {
          mobile: $('#mPhone').val(),
          openId: app.openId
        },
        beforesend: function() {
          $('#writePhone').off('click');
        },
        complete: function() {
          $('.loading').hide();
        },
        success: function(rp) {
          if (999 == rp.code) {
            alert(rp.msg);
          } else {
            app.sendInfo.status = 1;
            app.sendInfo.text = $('#mPhone').val();
            $('#pPhone').text($('#mPhone').val());
            autocloseBar('.writePhone');
            autoshowBar('.haveprize');
          }
          console.log(rp);
        }
      })
    },
    initCanvas: function() {
      $('.area').hide();
      var canvas = document.getElementById('myCanvas'),
        ctx = canvas.getContext('2d');
      canvas.width = $('#myc').width();
      canvas.height = $('#myc').height();
      var w = canvas.width;
      var h = canvas.height;
      console.log(w, h);
      area = w * h;
      l = canvas.offsetLeft;
      t = canvas.offsetTop,
        img = new Image();
      img.width = w;
      img.height = h;
      var randomImg = function() {
        img.src = app.ticketBg;
      };
      var bindEvent = function() {
        canvas.addEventListener('touchmove', moveFunc, false);
        canvas.addEventListener('touchend', endFunc, false);
      };
      var moveFunc = function(e) {
        var touch = e.touches[0],
          posX = touch.clientX - l,
          posY = touch.clientY - t;
        ctx.beginPath();
        ctx.arc(posX, posY, 15, 0, Math.PI * 2, 0);
        ctx.fill();
      };
      var endFunc = function(e) {
        var data = ctx.getImageData(0, 0, w, h).data,
          scrapeNum = 0;
        for (var i = 3, len = data.length; i < len; i += 4) {
          if (data[i] === 0) {
            scrapeNum++;
          }
        }
        if (scrapeNum > area * 0.7) {
          ctx.clearRect(0, 0, w, h);
          canvas.removeEventListener('touchmove', moveFunc, false);
          canvas.removeEventListener('touchend', endFunc, false);
          $('#myCanvas').on('click', app.getPrize);
        }
      }
      var init = function() {
        var imgC = new Image();
        imgC.src = "./images/ticket-back.png";
        imgC.onload = function() {
          ctx.drawImage(imgC, 0, 0, canvas.width, canvas.height);
        }
        ctx.fillStyle = "#ccc";
        ctx.fillRect(0, 0, w, h);
        randomImg();
        img.addEventListener('load', function() {
          canvas.style.backgroundImage = 'url(' + img.src + ')';
          console.log(parseInt($('html').css('fontSize')));
          var rem = parseInt($('html').css('fontSize'));
          canvas.style.backgroundSize = w / rem + 'rem ' + h / rem + 'rem';
          ctx.globalCompositeOperation = 'destination-out';
          bindEvent();
        });
      };
      init();
    },
    getPrize: function() {
      $('#myCanvas').off('click');
      var key=$('#myCanvas').attr('key');
      if (Number(key)) {
        console.log('status'+app.sendInfo.status);
        if (app.sendInfo.status) {
          autoshowBar('.haveprize');
          $('#pPhone').text(app.sendInfo.text);
        } else {
          autoshowBar('.writePhone');
          $('#writePhone').off('click');
          $('#writePhone').on('click', app.sendPhone);
        }
      } else {
        autoshowBar('.noGoods');
      }
    }
  }
  app.init();
})
